package com.self.springframework.beans.factory.xml;

import com.self.springframework.beans.factory.support.AbstractBeanDefinitionReader;
import com.self.springframework.beans.factory.support.BeanDefinitionRegistry;
import com.self.springframework.core.io.Resource;
import com.self.springframework.core.io.ResourceLoader;
import org.w3c.dom.Document;

import java.io.InputStream;

/**
 * 加载XML文件
 * 解析XML文档
 * 注册BeanDefinition
 * 处理嵌套的XML文件
 */
public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

    private DocumentLoader documentLoader = new DefaultDocumentLoader();


    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
        super(registry);
    }

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {
        super(registry, resourceLoader);
    }

    @Override
    public void loadBeanDefinitions(Resource resource) {
        try (InputStream inputStream = resource.getInputStream()) {
            doLoadBeanDefinitions(inputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void loadBeanDefinitions(Resource... resources) {
        for (Resource resource : resources) {
            loadBeanDefinitions(resource);
        }
    }

    @Override
    public void loadBeanDefinitions(String location) {
        ResourceLoader resourceLoader = getResourceLoader();
        Resource resource = resourceLoader.getResource(location);
        loadBeanDefinitions(resource);
    }

    @Override
    public void loadBeanDefinitions(String... locations) {
        for (String location : locations) {
            loadBeanDefinitions(location);
        }
    }

    private void doLoadBeanDefinitions(InputStream inputStream) {
        Document doc = this.doLoadDocument(inputStream);
        this.registerBeanDefinitions(doc,inputStream);

    }

    private Document doLoadDocument(InputStream inputStream) {
        return this.documentLoader.loadDocument(inputStream);
    }

    private void registerBeanDefinitions(Document doc, InputStream inputStream) {
        DefaultBeanDefinitionDocumentReader documentReader = new DefaultBeanDefinitionDocumentReader();
        documentReader.registerBeanDefinitions(doc,getRegister());
    }
}
